<template>
  <view class="content p-2.5">
    <view class="content_box">
      <view class="bg-[#fff] p-2.5 mb-3.5 rounded-[20rpx]">
        <!-- <u--textarea v-model="params.name" border="none" placeholder="请填写商品名称..."></u--textarea> -->
        <u--form labelPosition="left" :model="params" ref="uForm" labelWidth="100">
          <u-form-item label="商品名称" prop="params.name" borderBottom ref="item1">
            <u--input v-model="params.name" border="none" placeholder="请填写商品名称"></u--input>
          </u-form-item>
        </u--form>
      </view>
    </view>
    <view class="content_box">
      <view class="bg-[#fff] p-2.5 mb-3.5 rounded-[20rpx]">
        <u--textarea v-model="params.info" border="none" placeholder="请填写商品介绍..."></u--textarea>
        <u-upload :fileList="fileList1" accept="image" @afterRead="afterRead" @delete="deletePic" name="1" multiple :maxCount="9" :max-size="5 * 1024 * 1024" @oversize="oversize"></u-upload>
        <view style="font-size: 24rpx;color: #666666">请上传头部 背部 腹部 手部 脚部的照片</view>
        <u-upload :fileList="fileList3" accept="video" @afterRead="afterRead" @delete="deletePic" name="3" multiple :maxCount="1" :max-size="20 * 1024 * 1024" @oversize="oversize"></u-upload>
        <view style="font-size: 24rpx;color: #666666">上传视频</view>
      </view>
      <view class=" bg-[#fff] p-2.5 mb-3.5 rounded-[20rpx]">
        <u--form labelPosition="left" :model="params" ref="uForm" labelWidth="100">
          <u-form-item label="长度" prop="params.goodsLength" borderBottom ref="item1">
            <u--input v-model="params.goodsLength" border="none" type="digit" placeholder="请填写长度(厘米)"></u--input>
          </u-form-item>
          <u-form-item label="重量" prop="params.weight" borderBottom ref="item1">
            <u--input v-model="params.weight" border="none" type="digit" placeholder="请填写重量(克)"></u--input>
          </u-form-item>
          <u-form-item label="数量" prop="params.num" borderBottom ref="item1">
            <u--input v-model="params.num" border="none" type="number" placeholder="请填写数量"></u--input>
          </u-form-item>
        </u--form>
      </view>
      <view class=" bg-[#fff] p-2.5 rounded-[20rpx] mb-3.5">
        <u--form labelPosition="left" :model="params" ref="uForm" labelWidth="100">
          <!-- <u-form-item label="商品原价" prop="params.oldPrice" borderBottom ref="item1">
            <u--input v-model="params.oldPrice" border="none" type="digit" placeholder="请填写商品原价"></u--input>
          </u-form-item> -->
          <u-form-item label="商品价格" prop="params.price" borderBottom ref="item1">
            <u--input v-model="params.price" border="none" type="digit" placeholder="请填写商品价格"></u--input>
          </u-form-item>
          <!-- <u-form-item label="商品库存" prop="params.stock" borderBottom ref="item1">
            <u--input v-model="params.stock" border="none" type="number" placeholder="请填写商品库存"></u--input>
          </u-form-item> -->
          <u-form-item label="商品分类" prop="typeName" borderBottom ref="item1" @click="showType = true">
            <u--input v-model="params.typeName" disabled disabledColor="#ffffff" placeholder="请选择商品分类" border="none"></u--input>
            <u-icon slot="right" name="arrow-right"></u-icon>
          </u-form-item>
          <u-form-item label="宠物状态" prop="oldTypeName" borderBottom ref="item1" @click="showOldType = true">
            <u--input v-model="params.oldTypeName" disabled disabledColor="#ffffff" placeholder="请选择宠物状态" border="none"></u--input>
            <u-icon slot="right" name="arrow-right"></u-icon>
          </u-form-item>
          <u-form-item label="喂食记录" prop="recordList" borderBottom ref="item1" @click="chooseTime()">
            <u--input v-model="params.recordList" disabled disabledColor="#ffffff" placeholder="请添加喂食记录" border="none"></u--input>
            <u-icon slot="right" name="arrow-right"></u-icon>
          </u-form-item>
          <u-form-item label="售后天数" prop="afterDay" borderBottom ref="item1">
            <u--input v-model="params.afterDay" placeholder="请填写售后天数" type="number" border="none"></u--input>
          </u-form-item>
          <u-form-item label="是否保育" prop="brandName" borderBottom ref="item1" @click="showBrand = true">
            <u--input v-model="params.brandName" disabled disabledColor="#ffffff" placeholder="请选择是否保育" border="none"></u--input>
            <u-icon slot="right" name="arrow-right"></u-icon>
          </u-form-item>
          <view class="bg-[#fff] p-2.5 mb-3.5 rounded-[20rpx]" v-if="params.brandName == '保育'">
            <u-upload :fileList="fileList2" @afterRead="afterRead" @delete="deletePic" name="2" multiple :maxCount="3" :max-size="5 * 1024 * 1024" @oversize="oversize"></u-upload>
            <view style="font-size: 24rpx;color: #666666">请上传繁育许可证（照片3张上限）</view>
          </view>
        </u--form>
      </view>
      <view class=" bg-[#fff] p-2.5 rounded-[20rpx]">
        <u--form labelPosition="left" :model="params" ref="uForm" labelWidth="100">
          <u-form-item label="地址" prop="params.districts" borderBottom ref="item1">
            <uni-data-picker v-model="params.districtsCode" :localdata="areaList" placeholder="请选择地区" popup-title="请选择地区" @change="onchange"></uni-data-picker>
          </u-form-item>
          <u-form-item label="详细地址" prop="params.locationsName" borderBottom ref="item1">
            <u--textarea v-model="params.locationsName" border="none" autoHeight placeholder="请输入详细地址"></u--textarea>
            <view slot="right" style="color: #2979FF" @click="handleMap">获取位置</view>
          </u-form-item>
        </u--form>
      </view>
    </view>
    <!-- <view class="agreement">本人已阅读并签署<text class="link" @click="goProtocol(1)">《用户服务协议》</text></view> -->
    <view class="protocol">
      <u-checkbox-group v-model="checkboxValue" placement="column">
        <u-checkbox :name="1"></u-checkbox>
      </u-checkbox-group>
      本人已阅读并签署
      <text class="link" @click="goProtocol(1)">《发布商品需知》</text>
        和
        <text class="link" @click="goProtocol(4)">《商家入驻协议》</text>
    </view>
    <view class="but">
      <u-button color="#f56c6c" type="primary" @click="handleSend" text="发布商品"></u-button>
    </view>
    <!-- 商品分类 -->
    <u-picker :show="showType" :columns="typeList" keyName="configName" @cancel="showType = false" @confirm="handleRecharge"></u-picker>
    <u-picker :show="showBrand" :columns="brandList" keyName="configName" @cancel="showBrand = false" @confirm="handleBrand"></u-picker>
    <u-picker :show="showOldType" :columns="oldTypeList" keyName="configName" @cancel="showOldType = false" @confirm="handleOldType"></u-picker>
    <u-calendar color="#f56c6c" monthNum="25" :show="showTime" mode="multiple" :minDate="minDate" :maxDate="maxDate" @confirm="handleTime" @close="showTime = false"></u-calendar>
  </view>
</template>
<script>
import {
  getByKeyApi,
  addGoodsApi,
  getGoodsApi,
  getAreaListApi,
  getAddressApi,
} from "@/sheep/api/index";
import { baseUrl } from "@/sheep/request/baseUrl";

const d = new Date();
const year = d.getFullYear();
let month = d.getMonth() + 1;
month = month < 10 ? `0${month}` : month;
const date = d.getDate();

export default {
  name: "index",
  data() {
    return {
      areaList: [],
      showTheme: false,
      typeList: [],
      brandList: [],
      oldTypeList: [],
      showType: false,
      showBrand: false,
      showOldType: false,
      showTime: false,
      fileList1: [],
      fileList2: [],
      fileList3: [],
      params: {
        type: "",
        typeName: "",
        brand: "",
        brandName: "",
        oldType: "",
        oldTypeName: "",
        name: "",
        price: "",
        info: "",
        stock: 1,
        status: "0",
        record: "",
        recordList: "",
        img: "",
        licenseImg: "",
        goodsLength: "",
        weight: "",
        num: "",
        afterDay: "",
        province: "",
        city: "",
        districts: "",
        locationsName: "",
        video: "",
        districtsCode: "",
      },
      minDate: `${year - 2}-${month}-${date}`,
      maxDate: `${year}-${month}-${date}`,
      checkboxValue: [0],
    };
  },
  onShow() {
    this.getTypeList();
    this.getBrandList();
    this.getOldTypeList();
  },
  onLoad(options) {
    this.getArea();
    if (options?.goodsId) {
      getGoodsApi(options?.goodsId).then((res) => {
        this.params = res.data;
        this.params.status = "0";
        this.params.districtsCode = Number(res.data.districtsCode);
        res.data.img.split(",").forEach((item) => {
          this.fileList1.push({
            url: item,
          });
        });
        res.data.licenseImg?.split(",").map((item) => {
          this.fileList2.push({
            url: item,
          });
        });
        res.data.video?.split(",").map((item) => {
          this.fileList3.push({
            url: item,
          });
        });
      });
    }
  },
  methods: {
    handleMap() {
      let that = this;
      uni.showLoading({ title: "获取位置中" });
      uni.getLocation({
        type: "gcj02", //返回可以用于uni.openLocation的经纬度
        success: function (res) {
          const latitude = res.latitude;
          const longitude = res.longitude;
          getAddressApi({ location: latitude + "," + longitude }).then(
            (res) => {
              that.params.locationsName = res.data;
              uni.hideLoading();
            }
          );
        },
        fail: function (err) {
          uni.hideLoading();
          uni.showToast({
            title: "获取位置失败",
            icon: "none",
          });
        },
      });
    },
    onchange(e) {
      const value = e.detail.value;
      if (value.length > 0) {
        this.params.province = value[0].text;
        this.params.city = value[1].text;
        this.params.districts = value[2].text;
        this.params.districtsCode = value[2].value;
      } else {
        this.params.province = "";
        this.params.city = "";
        this.params.districts = "";
        this.params.districtsCode = "";
      }
    },
    getArea() {
      getAreaListApi().then((res) => {
        this.areaList = this.filterAreaName(res.data);
      });
    },
    filterAreaName(data) {
      // if(!(data?.length <= 0)){
      // 等价于
      if (!data || data.length <= 0) {
        // 递归的出口
        return null;
      }
      return data.map((x) => {
        // 循环数据
        const model = {
          // 把后端返回过来的数据里面的键给替换成我想要的键
          children: x.children,
          text: x.name,
          value: x.areaCode,
        };
        const children = this.filterAreaName(x.children); // 子级数据

        if (children) {
          // 一直往下循环查找有没有children这个键，如果有就直接添加一个子级字段名，这个字段名就是存子级数据
          model.children = children;
        }
        return model; // 返回这个数据
      });
    },
    goProtocol(value) {
      uni.navigateTo({ url: "/pages/protocol/index?type=" + value });
    },
    // 文件超出大小限制
    oversize() {
      uni.showToast({
        title: "上传最大不能超过5M",
        icon: "none",
      });
    },
    chooseTime() {
      this.showTime = true;
    },
    async getTypeList() {
      let res = await getByKeyApi("goods_type");
      this.typeList = [res.data];
    },
    async getBrandList() {
      let res = await getByKeyApi("brand");
      this.brandList = [res.data];
    },
    async getOldTypeList() {
      let res = await getByKeyApi("old_type");
      this.oldTypeList = [res.data];
    },

    handleTime(e) {
      this.params.recordList = e;
      this.showTime = false;
    },
    handleRecharge(e) {
      this.params.typeName = e.value[0].configName;
      this.params.type = e.value[0].businessConfigId;
      this.showType = false;
    },
    handleBrand(e) {
      this.params.brandName = e.value[0].configName;
      this.params.brand = e.value[0].businessConfigId;
      this.showBrand = false;
    },
    handleOldType(e) {
      this.params.oldTypeName = e.value[0].configName;
      this.params.oldType = e.value[0].businessConfigId;
      this.showOldType = false;
    },
    handleSend() {
      if (!this.checkboxValue[0]) {
        uni.showToast({
          title: "请同意发布商品需知",
          icon: "none",
        });
        return;
      }
      if (!this.params.name) {
        uni.showToast({
          title: "请填写商品名称",
          icon: "none",
        });
        return;
      }
      if (this.fileList1.length == 0) {
        uni.showToast({
          title: "请上传图片",
          icon: "none",
        });
        return;
      }
      if (!this.params.info) {
        uni.showToast({
          title: "请填写商品介绍",
          icon: "none",
        });
        return;
      }
      if (!this.params.price) {
        uni.showToast({
          title: "请填写商品价格",
          icon: "none",
        });
        return;
      }
      if (!this.params.stock) {
        this.params.stock = 1;
      }
      if (!this.params.type) {
        uni.showToast({
          title: "请选择商品分类",
          icon: "none",
        });
        return;
      }
      if (!this.params.districts) {
        uni.showToast({
          title: "请选择所在地址",
          icon: "none",
        });
        return;
      }
      if (!this.params.locationsName) {
        uni.showToast({
          title: "请输入详细地址",
          icon: "none",
        });
        return;
      }
      if (Array.isArray(this.fileList1)) {
        if (this.fileList1.length > 0) {
          this.fileList1.forEach((item, index) => {
            if (item.ossId == undefined || item.ossId == "undefined") {
              uni.showToast({
                title: "图片上传有误",
                icon: "none",
              });
              return;
            }
            if (
              item.url == undefined ||
              item.url == "undefined" ||
              item.url == null
            ) {
              return;
            }
            if (!this.params.img) {
              this.params.img = item.url;
            } else {
              this.params.img = this.params.img + "," + item.url;
            }
          });
        } else {
          this.params.img = "";
        }
      }
      if (Array.isArray(this.fileList3)) {
        if (this.fileList3.length > 0) {
          this.fileList3.forEach((item, index) => {
            if (item.ossId == undefined || item.ossId == "undefined") {
              uni.showToast({
                title: "视频上传有误",
                icon: "none",
              });
              return;
            }
            if (
              item.url == undefined ||
              item.url == "undefined" ||
              item.url == null
            ) {
              return;
            }
            if (!this.params.video) {
              this.params.video = item.url;
            } else {
              this.params.video = this.params.video + "," + item.url;
            }
          });
        }
      }
      if (Array.isArray(this.fileList2)) {
        if (this.fileList2.length > 0) {
          this.fileList2.forEach((item, index) => {
            if (
              item.url == undefined ||
              item.url == "undefined" ||
              item.url == null
            ) {
              return;
            }
            if (index === 0) {
              this.params.licenseImg = item.url;
            } else {
              this.params.licenseImg = this.params.licenseImg + "," + item.url;
            }
          });
        } else {
          this.params.licenseImg = "";
        }
      }
      uni.showLoading({});
      addGoodsApi(this.params).then((res) => {
        uni.hideLoading();
        uni.showToast({
          title: res.msg,
          icon: "none",
        });
        if (res.code == 200) {
          setTimeout(() => {
            uni.redirectTo({
              url: "/pages/mygoods/index?type=0",
            });
          }, 1000);
        }
      });
    },
    // 上传图片
    async afterRead(event) {
      let lists = [].concat(event.file);
      let fileListLen = this[`fileList${event.name}`].length;
      lists.map((item, index) => {
        this[`fileList${event.name}`].push({
          ...item,
          status: "uploading",
          message: "上传中",
        });
      });
      for (let i = 0; i < lists.length; i++) {
        const result = await this.uploadFilePromise(lists[i].url, lists, event);
        console.log("result", result);
        let item = this[`fileList${event.name}`][fileListLen];
        this[`fileList${event.name}`].splice(
          fileListLen,
          1,
          Object.assign(item, {
            status: "success",
            message: "",
            url: result.url,
            name: result.fileName,
            ossId: result.ossId,
          })
        );
        fileListLen++;
      }
    },
    uploadFilePromise(url, lists, event) {
      let token = uni.getStorageSync("token");
      let headerToken = "Bearer " + token;
      return new Promise((resolve, reject) => {
        let a = uni.uploadFile({
          url: baseUrl + "/resource/oss/upload",
          filePath: url,
          name: "file",
          header: {
            Authorization: headerToken,
            clientId: "be7052a7e4f802c20df10a8d131adb12",
          },
          formData: {
            user: "test",
          },
          success: (res) => {
            let data = JSON.parse(res.data);
            console.log("data", data);
            if (data.code == 200) {
              resolve(data.data);
            } else {
              if (lists.length > 0) {
                lists.map((item, index) => {
                  this[`fileList${event.name}`].splice(index, 1);
                });
              }
              uni.showToast({
                title: data.msg,
                icon: "none",
              });
            }
          },
        });
      });
    },
    // 删除图片
    deletePic(event) {
      this[`fileList${event.name}`].splice(event.index, 1);
    },
  },
};
</script>

<style scoped lang="scss">
.content {
  background-color: #f5f5f5;
  // height: 100vh;
  .agreement {
    width: 100%;
    text-align: center;
    color: #999999;
    font-size: 22rpx;
    margin-top: 10rpx;
  }
  .but {
    margin-top: 40rpx;
    margin-bottom: 80rpx;
  }
}
.release {
  width: 100rpx;
  height: 70rpx;
  font-size: 28rpx;
  border-radius: 10rpx;
  background-color: #3c9cff;
  color: #ffffff;
}

// 支付弹层
.pay {
  padding: 30rpx;

  .pay-title {
    font-size: 35rpx;
  }

  .pay-select {
    margin: 50rpx;
  }

  .pay-flex {
    display: flex;
    margin-top: 30rpx;

    ::v-deep .u-button {
      height: 84rpx !important;
      font-size: 30rpx;

      &:first-child {
        margin-right: 25rpx !important;
      }
    }
  }

  .surplus {
    margin-top: 35rpx;
    font-size: 25rpx;

    .surplus-num {
      margin-left: 15rpx;
    }
  }
}
.protocol {
  margin-top: 40rpx;
  font-size: 24rpx;
  color: #999;
  display: flex;
  .link {
    color: #2979ff;
  }
}
::v-deep.input-value-border {
  border: unset !important;
}
</style>
